<?php
declare (strict_types = 1);
namespace app\course\logic\note;

use app\common\logic\Common;
use think\facade\Config;
use app\common\exception\LogicException;
use app\course\model\note\Note as NoteModel;

/**
 * 笔记接口类
 */
class Note extends NoteModel
{

	/**
	 * 获取课程的笔记信息
	 * Author   亓官雨树<lucky.max@foxmail.com>
	 * Date 2020-04-13
	 */
	public function getList($param)
	{
        // 验证数据
        $this->getValidate()->scene('list')->failException()->check($param);
        $type       = $param['type'];
        $section_id = $param['section_id'];
        $mid        = static::$mid;
        if ( $type == 'all' ) {
            $map1 = [
                ['open_status', '=', 1],
            ];
            $map2 = [
                ['open_status', '=', 0],
                ['user_id', '=', $mid]
            ];

            $list = $this
                ->where('section_id', $section_id)
                ->where(function ($query) use ($map1, $map2) {
                    $query->whereOr([$map1, $map2]);
                })
                ->whereNull('delete_time')
                ->order('id DESC')
                ->paginate($this->getListRows());
        } elseif ( $type == 'my' ) {
            $list = $this
                ->where('section_id', $section_id)
                ->where('user_id', $mid)
                ->whereNull('delete_time')
                ->order('id DESC')
                ->paginate($this->getListRows());
        } else {
            throw new LogicException('参数错误');
        }

        foreach ($list as $key => $note) {
            $note->user = $note->user()->field('id,nick_name,avatar')->find();
        }

        return $list;
	}

    /**
     * 添加笔记
     * Author   亓官雨树<lucky.max@foxmail.com>
     * Date 2020-04-13
     */
    public function addNote($param)
    {
        // 验证数据
        $this->getValidate()->scene('add')->failException()->check($param);
        // 添加
        $param['user_id'] = request()->mid;
        // 内容过滤
        $param['content']  = app(Common::class)->filterSensitive($param['content'],$param['course_id'],'note');
        if ( !$this->data($param, true)->save() ) {
            throw new LogicException('添加失败');
        }

        return $this;
    }

    /**
     * 修改笔记
     * Author   亓官雨树<lucky.max@foxmail.com>
     * Date 2020-04-17
     */
    public function editNote($id, $param)
    {
        // 验证数据
        $this->getValidate()->scene('edit')->failException()->check($param);
        // 查找数据
        $note = $this->findOrFail($id);

        if ( $note->user_id != request()->mid ) {
            throw new LogicException('用户错误');
        }
        // 修改数据
        $note->content      = $param['content'];
        $note->open_status  = intval($param['open_status']);
        // 内容过滤
        $note->content      = app(Common::class)->filterSensitive($note->content,$id,'note_edit');
        if ( !$note->save() ) {
            throw new LogicException('修改失败');
        }

        return $note;
    }

}
